package edu.controller;

import edu.service.ScoreService;
import edu.vo.Score;
import edu.vo.ID.ScoreId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/scores")
public class ScoreController {

    @Autowired
    private ScoreService scoreService;

    /**
     * 保存成绩信息
     * @param score 成绩对象
     * @return 保存后的成绩对象
     */
    @PostMapping
    public ResponseEntity<Score> saveScore(@RequestBody Score score) {
        Score savedScore = scoreService.saveScore(score);
        return new ResponseEntity<>(savedScore, HttpStatus.CREATED);
    }

    /**
     * 根据 ID 获取成绩信息
     * @param id 成绩 ID
     * @return 成绩对象的 Optional 包装
     */
    @GetMapping("/{id}")
    public ResponseEntity<Score> getScoreById(@PathVariable ScoreId id) {
        Optional<Score> scoreOptional = scoreService.getScoreById(id);
        return scoreOptional.map(score -> new ResponseEntity<>(score, HttpStatus.OK))
                .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * 获取所有成绩信息
     * @return 成绩列表
     */
    @GetMapping
    public ResponseEntity<List<Score>> getAllScores() {
        List<Score> scores = scoreService.getAllScores();
        return new ResponseEntity<>(scores, HttpStatus.OK);
    }

    /**
     * 根据 ID 删除成绩信息
     * @param id 成绩 ID
     * @return 无内容响应
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteScoreById(@PathVariable ScoreId id) {
        scoreService.deleteScoreById(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 更新成绩信息
     * @param id 成绩 ID
     * @param score 新的成绩信息
     * @return 更新后的成绩对象
     */
    @PutMapping("/{id}")
    public ResponseEntity<Score> updateScore(@PathVariable ScoreId id, @RequestBody Score score) {
        Score updatedScore = scoreService.updateScore(id, score);
        return updatedScore != null ? new ResponseEntity<>(updatedScore, HttpStatus.OK)
                : new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}